export default {
  namespaced: true,
  state: {
    //存放购物车内商品
    //通过缓存获取购物车内容
    cart: uni.getStorageSync('cart_goods') || [],
  },
  mutations: {
    addCart(state, goods) {
      //将商品数据存入state
      //判断商品是否已经被添加购物车
      // const isAdd = state.cart.some(item => {
      //   return item.goods_id == goods.goods_id
      // })
      // 对添加进入商品数组进行简化
      const index = state.cart.findIndex(item => item.goods_id === goods.goods_id)

      //没有就添加进去
      if (index == "-1") {
        //给goods拼接一个数量属性
        goods = { ...goods, count: 1, checked: true }
        state.cart.push(goods)
        //存入缓存
        uni.setStorageSync('cart_goods', state.cart)
        console.log(state.cart);

      } else {
        //找到购物车内的那个商品,将数量加一
        // state.cart.forEach(item => {
        //   if (item.goods_id == goods.goods_id) {
        //     item.count++
        //   }
        // });
        state.cart[index].count++
        uni.setStorageSync('cart_goods', state.cart)
        console.log(state.cart);

      }

    },
    //单选框选中与取消
    checkCart(state, payload) {
      console.log(payload);

      //获取到当前点击的数据,将该i的数据进行check 数据取反
      state.cart.forEach((item) => {
        if (item.goods_id === payload) {
          item.checked = !item.checked;
        }
      });
      //将数据进行缓存
      uni.setStorageSync('cart_goods', state.cart)

    },
    // 购物车数量的修改
    goods_count_change(state, payload) {
      //对数量进行更改
      state.cart[payload.index].count += payload.params
      //数据缓存
      uni.setStorageSync('cart_goods', state.cart)

    },
    goods_remove(state, payload) {
      state.cart.splice(payload, 1)
    },

    //修改按钮的选中状态
    goods_checked(state, payload) {
      console.log(payload);

      state.cart.forEach(item => item.checked = payload)
      uni.setStorageSync('cart_goods', state.cart)
    }

  },
  actions: {

  },
  getters: {
    cart_count: state => state.cart.reduce((sum, item) => item.count + sum, 0),
    checkedCartList: state => state.cart.filter(item => item.checked == true),
    // 要支付的商品的总价格 checkedPrice
    checkedPrice(state, getters) {
      return getters.checkedCartList.reduce((price, item) => price += item.count * item.goods_price, 0);
    },
    // 要支付的商品的总数量 checkedCount
    checkedCount(state, getters) {
      return getters.checkedCartList.reduce((count, item) => count += item.count, 0)
    }

  }}